package com.foton.logistic.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.foton.logistic.R;
import com.foton.logistic.base.BaseActivity;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.foton.logistic.view.city.City;
import com.foton.logistic.view.city.DBHelper;
import com.foton.logistic.view.city.DatabaseHelper;
import com.foton.logistic.view.city.MyLetterListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class CityActivity extends BaseActivity implements OnScrollListener {

    @InjectView(R.id.ft_ui_city_listview)
    public ListView personList;
    @InjectView(R.id.ft_ui_city_letterlistview)
    public MyLetterListView letterListView; // A-Z listview

    private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
    private String[] sections;// 存放存在的汉语拼音首字母
    private ArrayList<City> allCityList; // 所有城市列表
    private ArrayList<City> cityList;// 城市列表
    private ArrayList<City> resultCityList;// 搜索城市列表
    private DatabaseHelper helper;
    private ReceiveBroadcast receiveBroadcast;
    private CityAdapter adapter;
    int statusBarHeight;//状态栏高度

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ft_ui_city);
        ButterKnife.inject(this);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiveBroadcast);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void init() {
        registerBroad();
        statusBarHeight = OptionUtil.getStatusBarHeight(CityActivity.this);
        setTitleText(getString(R.string.title10)+ SharedUtil.getChooseCity(this));
        setTitleTextVisibility(View.VISIBLE);
        setBackLayoutVisibility(View.VISIBLE);
        allCityList = new ArrayList<City>();
        resultCityList = new ArrayList<City>();
        helper = new DatabaseHelper(this);
        letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
        alphaIndexer = new HashMap<String, Integer>();
        personList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position >= 1) {
                    chooseCity(allCityList.get(position).getName(),allCityList.get(position).getCode());
                }
            }
        });
        personList.setAdapter(adapter);
        personList.setOnScrollListener(this);
        cityInit();
        setAdapter(allCityList);
    }

    private void cityInit() {
        City city = new City("DW", "定位城市","0"); // 当前定位城市
        allCityList.add(city);
        cityList = getCityList();
        allCityList.addAll(cityList);
    }

    void chooseCity(String city,String code){
        SharedUtil.saveChooseCity(this,city,code);
        finishSelf();
    }

    @SuppressWarnings("unchecked")
    private ArrayList<City> getCityList() {
        DBHelper dbHelper = new DBHelper(this);
        ArrayList<City> list = new ArrayList<City>();
        try {
            dbHelper.createDataBase();
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.rawQuery("SELECT  PROVCODE, MDMPROVNUM, MDMPROVNAME, CITYCODE, MDMCITYNUM, MDMCITYNAME" +
                    " FROM ifoton_city ORDER BY CITYCODE", null);
            City city;
            while (cursor.moveToNext()) {
                city = new City(cursor.getString(3), cursor.getString(5), cursor.getString(4));
                list.add(city);
            }
            cursor.close();
            db.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(list, comparator);
        return list;
    }

    @SuppressWarnings("unchecked")
    private void getResultCityList(String keyword) {
        DBHelper dbHelper = new DBHelper(this);
        try {
            dbHelper.createDataBase();
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            //SELECT PROVCODE,MDMPROVNUM,MDMPROVNAME,CITYCODE,MDMCITYNUM,MDMCITYNAME FROM ifoton_city WHERE MDMCITYNAME LIKE '%a%' OR CITYCODE LIKE '%c%' ORDER BY CITYCODE
            Cursor cursor = db.rawQuery(
                    "SELECT PROVCODE,MDMPROVNUM,MDMPROVNAME,CITYCODE,MDMCITYNUM,MDMCITYNAME FROM ifoton_city WHERE MDMCITYNAME LIKE \"%" + keyword
                            + "%\" or CITYCODE LIKE \"%" + keyword + "%\"", null);
            City city;
            Log.e("info", "length = " + cursor.getCount());
            while (cursor.moveToNext()) {
                city = new City(cursor.getString(3), cursor.getString(5), cursor.getString(4));
                resultCityList.add(city);
            }
            cursor.close();
            db.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(resultCityList, comparator);
    }

    /**
     * a-z排序
     */
    @SuppressWarnings("rawtypes")
    Comparator comparator = new Comparator<City>() {
        @Override
        public int compare(City lhs, City rhs) {
            String a = lhs.getPinyi().substring(0, 1);
            String b = rhs.getPinyi().substring(0, 1);
            int flag = a.compareTo(b);
            if (flag == 0) {
                return a.compareTo(b);
            } else {
                return flag;
            }
        }
    };

    private void setAdapter(List<City> list) {
        adapter = new CityAdapter(this, list);
        personList.setAdapter(adapter);
    }


    public class CityAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<City> list;
        final int VIEW_TYPE = 5;

        public CityAdapter(Context context, List<City> list) {
            this.inflater = LayoutInflater.from(context);
            this.list = list;
            this.context = context;
            alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                // 当前汉语拼音首字母
                String currentStr = getAlpha(list.get(i).getPinyi());
                // 上一个汉语拼音首字母，如果不存在为" "
                String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
                        .getPinyi()) : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = getAlpha(list.get(i).getPinyi());
                    alphaIndexer.put(name, i);
                    sections[i] = name;
                }
            }
        }

        @Override
        public int getViewTypeCount() {
            return VIEW_TYPE;
        }

        @Override
        public int getItemViewType(int position) {
            return position < 4 ? position : 4;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        ViewHolder holder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final TextView city;
            int viewType = getItemViewType(position);
            if (viewType == 0) { // 定位
                convertView = inflater.inflate(R.layout.ft_adapter_city_location, null);
                TextView locateHint = (TextView) convertView
                        .findViewById(R.id.ft_adapter_city_location_title);
                city = (TextView) convertView.findViewById(R.id.ft_adapter_city_location_content);
                if (!StringUtil.isEmpty(SharedUtil.getCity(context))){
                    city.setText(SharedUtil.getCity(context));
                }else {
                    city.setText(context.getString(R.string.location1));
                }
                city.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtil.isEmpty(SharedUtil.getCity(context))){
                            OptionUtil.addToast(context,context.getString(R.string.location1));
                        }else {
                            chooseCity(SharedUtil.getCity(context),SharedUtil.getCityCode(context));
                        }
                    }
                });
            } else {
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.ft_adapter_city_list_item, null);
                    holder = new ViewHolder();
                    holder.alpha = (TextView) convertView
                            .findViewById(R.id.ft_adapter_city_list_item_title);
                    holder.name = (TextView) convertView
                            .findViewById(R.id.ft_adapter_city_list_item_content);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                if (position >= 1) {
                    holder.name.setText(list.get(position).getName());
                    String currentStr = getAlpha(list.get(position).getPinyi());
                    String previewStr = (position - 1) >= 0 ? getAlpha(list
                            .get(position - 1).getPinyi()) : " ";
                    if (!previewStr.equals(currentStr)) {
                        holder.alpha.setVisibility(View.VISIBLE);
                        holder.alpha.setText(currentStr);
                    } else {
                        holder.alpha.setVisibility(View.GONE);
                    }
                }
            }
            return convertView;
        }

        private class ViewHolder {
            TextView alpha; // 首字母标题
            TextView name; // 城市名字
        }
    }

    private class ResultListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private ArrayList<City> results = new ArrayList<City>();

        public ResultListAdapter(Context context, ArrayList<City> results) {
            inflater = LayoutInflater.from(context);
            this.results = results;
        }

        @Override
        public int getCount() {
            return results.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.ft_adapter_city_list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.name = (TextView) convertView
                        .findViewById(R.id.ft_adapter_city_list_item_content);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.name.setText(results.get(position).getName());
            return convertView;
        }

        class ViewHolder {
            TextView name;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private boolean isScroll = false;

    private class LetterListViewListener implements
            MyLetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            isScroll = false;
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                personList.setSelection(position);
            }
        }
    }


    // 获得汉语拼音首字母
    private String getAlpha(String str) {
        if (str == null) {
            return "#";
        }
        if (str.trim().length() == 0) {
            return "#";
        }
        char c = str.trim().substring(0, 1).charAt(0);
        // 正则表达式，判断首字母是否是英文字母
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase();
        } else if (str.equals("0")) {
            return "定位";
        } else if (str.equals("1")) {
            return "最近";
        } else if (str.equals("2")) {
            return "热门";
        } else if (str.equals("3")) {
            return "全部";
        } else {
            return "#";
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_TOUCH_SCROLL
                || scrollState == SCROLL_STATE_FLING) {
            isScroll = true;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        if (!isScroll) {
            return;
        }
    }

    LinearLayout container;

    public void showSearchWindow(Context context, View view) {
        PopupWindow popupWindow = getSearchWindow(context);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    int[] xy = {1,1};
                    container.getLocationOnScreen(xy);
                    if (xy[1]<statusBarHeight){
                        container.setPadding(0,statusBarHeight-xy[1],0,0);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, 100);
    }

    public PopupWindow getSearchWindow(final Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.ft_view_city_search, null, false);
        final ListView listView = (ListView) view.findViewById(R.id.ft_view_city_search_listview);
        final TextView emptyText = (TextView) view.findViewById(R.id.ft_view_city_search_empty);
        TextView cancelText = (TextView) view.findViewById(R.id.ft_view_city_search_cancel);
        EditText searchEditText = (EditText) view.findViewById(R.id.ft_view_city_search_content);
        container = (LinearLayout) view.findViewById(R.id.ft_view_city_search_container);
        final ResultListAdapter adapter = new ResultListAdapter(context, resultCityList);
        listView.setAdapter(adapter);
        final PopupWindow popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        OptionUtil.openKeyBoard(new Handler(), CityActivity.this, 100);
        popupWindow.setBackgroundDrawable(new BitmapDrawable()); //使按返回键能够消失
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                chooseCity(resultCityList.get(arg2).getName(),resultCityList.get(arg2).getCode());
                popupWindow.dismiss();
                OptionUtil.closeKeyBoard(CityActivity.this);
                finishSelf();
            }

        });
        cancelText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popupWindow.dismiss();
            }

        });
        searchEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString() == null || "".equals(s.toString())) {
                    listView.setBackgroundResource(R.color.clear);
                    resultCityList.clear();
                    adapter.notifyDataSetChanged();
                } else {
                    listView.setBackgroundResource(R.color.white);
                    resultCityList.clear();
                    getResultCityList(s.toString());
                    if (resultCityList.size() <= 0) {
                        emptyText.setVisibility(View.VISIBLE);
                        listView.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                    } else {
                        emptyText.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);
                        adapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                OptionUtil.closeKeyBoard(CityActivity.this);
            }
        });
        return popupWindow;
    }

    @OnClick({R.id.ft_ui_city_search})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.ft_ui_city_search:
                showSearchWindow(CityActivity.this, view);
                break;
        }
    }

    private void registerBroad() {
        try {
            if (receiveBroadcast == null) {
                receiveBroadcast = new ReceiveBroadcast();
                IntentFilter filter = new IntentFilter();
                filter.addAction(BaseConstant.ACTION_LOCATION);
                registerReceiver(receiveBroadcast, filter);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class ReceiveBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                int type = intent.getIntExtra(BaseConstant.INTENT_TYPE, 0);
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}